import { Injectable } from '@nestjs/common';
import { MysqlService } from '../../database/mysql/mysql.service';
import { BusinessException } from '../../types/exception/business.exception';
import { ERR_MSG } from '../../types/errcode';
import { DogDto, DogUpdateDto } from './dto/dog.dto';

@Injectable()
export class DogService {
  constructor(private readonly _mysqlService: MysqlService) {}

  // 创建狗
  async create(dog: DogDto) {
    const newDog = this._mysqlService.dogRepository.create(dog);
    await this._mysqlService.dogRepository.save(newDog);
    return { msg: '创建成功' };
  }

  // 查询所有狗
  async findAll() {
    const [list, total] = await this._mysqlService.dogRepository.findAndCount();
    return { list, total };
  }

  // 更新狗
  async update(dog: DogUpdateDto) {
    if (!dog.id) {
      throw new BusinessException(ERR_MSG.CUSTOM, 'id不能为空');
    }

    // 判断当前id是否存在（使用 findOne 正确查询）
    const existingDog = await this._mysqlService.dogRepository.findOneBy({
      id: dog.id,
    });
    if (!existingDog) {
      throw new BusinessException(ERR_MSG.CUSTOM, 'id不存在');
    }

    await this._mysqlService.dogRepository.update(dog.id, dog);
    return { msg: '更新成功' };
  }
}
